/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { ReactNode } from 'react';
import type { BasicLayoutProps as ProLayoutProps } from '@ant-design/pro-layout';
import { Button, Result, Tabs } from 'antd';
import { useDispatch, useSelector } from 'umi';
import { ConnectState } from '@/models/connect';
import { TabItem, UpdateTabsType, useRecordTab } from '@/utils/hooks/pageTabs';
import { getMatchMenu } from '@umijs/route-utils';
import Authorized from '@/utils/Authorized';
import { noop } from 'lodash';
import KbIframe from '@/components/iframe/';
import styles from './index.less';
import { getAuthorityByPathname } from './_utils';

const { TabPane } = Tabs;

type OnEdit = (type: UpdateTabsType, tabItem: TabItem) => void;

export interface ChildrenMap {
  [key: string]: ReactNode;
}
interface PageTabsProps {
  route: ProLayoutProps['route'] & {
    authority: string[];
  };
  onEdit?: OnEdit;
  childrenMap?: ChildrenMap;
  noMatch?: any;
}

const PageTabs: React.FC<PageTabsProps> = (props) => {
  const { route, onEdit = noop, childrenMap } = props;
  const dispatch = useDispatch();
  const { collapsed, winSize } = useSelector((state: ConnectState) => state.global);
  const { currentUser } = useSelector((state: ConnectState) => state.user);
  const left = winSize === 'sm' || winSize === 'xs' ? 0 : collapsed ? 48 : 208;
  const [tabs, activeKey, updateTabs] = useRecordTab(route.routes as any);

  const handleEdit = (name: any) => {
    const { pathname: currentPathname } = updateTabs('remove', name);
    onEdit('remove', { name, pathname: currentPathname });
  };
  const handleChange = (name: string) => updateTabs('change', name);

  const { managerInfo } = currentUser || {};

  // 获取权限
  const authorized = (pathname: string) => {
    let menus: any = [];
    route
      .routes!.filter((item: any) => item.name && item.routes)
      .forEach(({ routes = [], ...item }) => {
        menus.push(item);
        menus.push(...routes);
      });
    menus = menus.map((item: any) => ({
      authority: getAuthorityByPathname(item.path),
      ...item,
      key: item.path,
    }));
    const matchedMenu = getMatchMenu(pathname || '/', menus).pop() || {
      authority: undefined,
    };
    return matchedMenu;
  };

  // 重置权限
  const getMenuAuth = () => {
    dispatch({
      type: 'user/fetchCurrent',
    });
  };

  const noMatch = (
    <Result
      status={403}
      title='403'
      subTitle={`你好！权限使用请联系管理员-${managerInfo ? managerInfo.name : ''}：${
        managerInfo ? managerInfo.mobile : ''
      }`}
      extra={
        <Button type='primary' onClick={getMenuAuth}>
          刷新
        </Button>
      }
    />
  );

  return (
    <div className={styles['tab-wrap']}>
      <div className={styles.tab}>
        <Tabs
          type='editable-card'
          hideAdd
          activeKey={activeKey}
          onEdit={handleEdit}
          onChange={handleChange}
          tabBarStyle={{ left }}
        >
          {tabs?.map((item) => (
            <TabPane tab={item.name} key={item.name} closable={tabs.length > 1}>
              <Authorized authority={authorized(item.pathname)?.authority} noMatch={noMatch}>
                <KbIframe pathname={item.pathname}>
                  {childrenMap ? childrenMap[item.pathname] : null}
                </KbIframe>
              </Authorized>
            </TabPane>
          ))}
        </Tabs>
      </div>
    </div>
  );
};

export default PageTabs;
